package study.ttl.common.system;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import study.ttl.common.enums.OrderStatusEnum;
import study.ttl.entity.Orders;
import study.ttl.service.OrdersService;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 处理订单超时
 */
@Component
@Slf4j
public class OrdersSchedule {

    @Autowired
    private OrdersService ordersService;

    @Scheduled(fixedRate = 1, timeUnit = TimeUnit.MINUTES) // 每分钟执行一次
    public void orderTask(){
        log.info("==========================开始处理订单超时==============================");
        // 查询待支付的订单 15分钟过期
        List<Orders> noPayOrders = ordersService.selectByStatus(OrderStatusEnum.NOT_PAY.name());
        for (Orders orders : noPayOrders) {
            String createTime = orders.getCreateTime();
            DateTime dateTime = DateUtil.parse(createTime); // 获取订单创建时间
            long between = new Date().getTime() - dateTime.getTime();
            if (between > 15 * 60 * 1000) {
                ordersService.cancelOrder(orders);
            }
        }

        // 拼团中的订单 拼团24小时超时
        List<Orders> inGroupOrders = ordersService.selectByStatus(OrderStatusEnum.IN_GROUP.name());
        for (Orders orders : inGroupOrders) {
            String createTime = orders.getCreateTime();
            DateTime dateTime = DateUtil.parse(createTime); // 获取订单创建时间
            long between = new Date().getTime() - dateTime.getTime();
            if (between > 24 * 60 * 60 * 1000) {
                ordersService.cancelGroupOrder(orders);
            }
        }
        log.info("==========================结束处理订单超时==============================");
    }

}
